(function (window, $) {
    "use strict";
    var Navbar = function () {
        /**
         *  默认配置
         */
        this.config = {
            elem: undefined, //容器
            data: undefined, //数据源
            url: undefined, //数据源地址
            type: 'GET',    //读取方式
            spreadOne: false //设置是否只展开一个二级菜单
        };
        this.v = '1.0.0';
    };

    /**
     * 渲染
     * @param {Object} options
     */
    Navbar.prototype.render = function (options) {
        var _that = this;
        _that.config.data = undefined;
        $.extend(true, _that.config, options);

        var _config = _that.config;
        if (typeof (_config.elem) !== 'string' && typeof (_config.elem) !== 'object') {
            //  common.throwError('Navbar error: elem参数未定义或设置出错，具体设置格式请参考文档API.');
        }
        var $container;
        if (typeof (_config.elem) === 'string') {
            $container = $('' + _config.elem + '');
        }
        if (typeof (_config.elem) === 'object') {
            $container = _config.elem;
        }
        if ($container.length === 0) {
            //   common.throwError('Navbar error:找不到elem参数配置的容器，请检查.');
        }

        if (_config.data === undefined && _config.url === undefined) {
            // common.throwError('Navbar error:请为Navbar配置数据源.')
        }
        if (_config.data !== undefined && typeof (_config.data) === 'object') {
            var html = getHtml(_config.data, 0);
            $container.html(html);
            _that.config.elem = $container;
        } else {
            $.ajax({
                type: _config.type,
                url: _config.url,
                async: false, //_config.async,
                dataType: 'json',
                success: function (result, status, xhr) {
                    var html = getHtml(result, 0);
                    $container.html(html);
                },
                complete: function (xhr, status) {
                    _that.config.elem = $container;
                }
            });
        }
        var $ul = $container.children('ul');
        $ul.find('li.admin-tree-item').each(function () {
            $(this).on('click', function (e) {
                if (!$(this).hasClass('admin-tree-itemed')) {
                    $(this).addClass('admin-tree-itemed');
                    $(this).children('a').find('.admin-arrow').addClass('arrow-bottom');
                }
                $(this).siblings().removeClass('admin-tree-itemed');
                if ($(this).parent().hasClass('admin-nav-tree-main')) {
                    $(this).siblings().find('.admin-tree-itemed').removeClass('admin-tree-itemed');
                }
                e.stopPropagation();
            });
        })
        return _that;
    };

    /**
     * 绑定事件
     * @param {String} events
     * @param {Function} callback
     */
    Navbar.prototype.on = function (events, callback) {
        var that = this;
        var _con = that.config.elem;
        if (typeof (events) !== 'string') {
            // common.throwError('Navbar error:事件名配置出错，请参考API文档.');
        }
        // var lIndex = events.indexOf('(');
        if (events === 'click') {
            _con.children('ul').find('li').each(function () {
                var $this = $(this);
                $this.on('click', function () {
                    var $a = $this.children('a');
                    var href = $a.data('url');
                    var id = $a.data('id');
                    var icon = $a.children('i:first').data('icon');
                    var title = $a.children('cite').text();
                    var data = {
                        elem: $a,
                        field: {
                            href: href,
                            icon: icon,
                            title: title,
                            id: id
                        }
                    };
                    callback(data);
                });
            });
        }
    };

    /**
     * 获取html字符串
     * @param {Object} data
     */
    function getHtml(data, index) {
        var $ul = $('<ul></ul>');
        $ul.addClass('admin-nav-tree');
        if (index == 0) {
            $ul.addClass('admin-nav-tree-main');
        }
        var leftNavOne,leftNavId;
        for (var i = 0; i < data.length; i++) {
            var $li = $('<li></li>');
            $li.addClass('admin-tree-item');
            if (data[i].children && data[i].children.length > 0) {
                var children = data[i].children;
                for (var t = 0; t < children.length; t++) {
                    leftNavOne = $.cookie("leftNavOne");
                    if (leftNavOne) {
                        leftNavOne=$.parseJSON(leftNavOne)
                        leftNavId = leftNavOne["id"];
                        if (children[t]["id"] == leftNavId) {
                            data[i].spread=true;
                            children[t].spread = true;
                        }
                    }
                }
            }

            leftNavOne = $.cookie("leftNavOne");
            if (leftNavOne) {
                leftNavOne=$.parseJSON(leftNavOne);
                leftNavId = leftNavOne["id"];
                if (data[i]["id"] == leftNavId) {
                    data[i].spread=true;
                }
            }
            if (data[i].spread) {
                $li.addClass('admin-tree-itemed');
            }
            var $a = $('<a></a>');
            $a.data('data', data[i]);
            $a.data('id', data[i].id);
            $a.data('url', data[i].href);
            $a.attr('title', data[i].title);
            if (index > 0) {
                for (var j = 0; j < index; j++) {
                    $a.append("<span style='width:10px;display: inline-block;'></span>");
                }
            }
            if (data[i].icon !== undefined && data[i].icon !== '' && data[i].hasIcon !== "0") {
                var icon = '<span class="icon-show ' + data[i].icon + '"></span>';
                $a.append(icon);
            }
            var txt = '<cite>' + data[i].title + '</cite>';
            $a.append(txt);
            if (data[i].children !== undefined && data[i].children !== null && data[i].children.length > 0) {
                $a.append('<span class="admin-arrow arrow-right"></span>');
            }
            $li.append($a);
            if (data[i].children !== undefined && data[i].children !== null && data[i].children.length > 0) {
                $li.append(getHtml(data[i].children, index + 1))
            }
            $ul.append($li);
        }
        return $ul
    }

    var ELEM = {};
    var globalTabIdIndex = 0;
    var AdminTab = function () {
        this.config = {
            elem: undefined,
            closed: true,   //是否包含删除按钮
            autoRefresh: false,
            contextMenu: false,
            onSwitch: undefined,
            openWait: true
        };
    };
    AdminTab.prototype.init = function (options) {
        var that = this;
        $.extend(true, that.config, options);
        var _config = that.config;
        if (typeof (_config.elem) !== 'string' && typeof (_config.elem) !== 'object') {
            //   common.throwError('Tab error: elem参数未定义或设置出错，具体设置格式请参考文档API.');
        }
        var $container;
        if (typeof (_config.elem) === 'string') {
            $container = $('' + _config.elem + '');
        }
        if (typeof (_config.elem) === 'object') {
            $container = _config.elem;
        }
        if ($container.length === 0) {
            // common.throwError('Tab error:找不到elem参数配置的容器，请检查.');
        }
        _config.elem = $container;
        ELEM.titleBox = $container.find('ul.admin-tab-title');
        ELEM.contentBox = $container.children('div.admin-tab-content');

        // 绑定菜单点击事件
        ELEM.titleBox.on('click', 'li', function () {
            that.tabChange($(this).data('id'));
        });
        // 初始化左右切换菜单按钮
        $container.find('.admin-tab-title-outer').on('click', '.admin-arrow', function () {
            var $t = $(this);
            var scrollLeft = ELEM.titleBox.scrollLeft();
            var w = ELEM.titleBox.width();
            var scrollWidth = ELEM.titleBox[0].scrollWidth;
            // 左移
            if ($t.hasClass('arrow-left')) {
                if (scrollLeft > 100) {
                    ELEM.titleBox.scrollLeft(scrollLeft - 100);
                } else {
                    ELEM.titleBox.scrollLeft(0);
                }
            }else {
            // 右移
                var l = scrollWidth - scrollLeft - w;
                if (l > 100) {
                    ELEM.titleBox.scrollLeft(scrollLeft + 100);
                } else {
                    ELEM.titleBox.scrollLeft(scrollWidth - w);
                }
            }
        });
        return that;
    };
    /**
     * 查询tab是否存在，如果存在则返回索引值，不存在返回-1
     * @param {String} id 标题
     */
    AdminTab.prototype.exists = function (id) {
        var that = ELEM.titleBox === undefined ? this.init() : this,
            tabIndex = -1;
        ELEM.titleBox.find('li').each(function (i, e) {
            var _id = $(this).data('id');
            if (_id === id) {
                tabIndex = i;
            }
        });
        return tabIndex;
    };

    /**
     * 添加选择卡，如果选择卡存在则获取焦点
     * @param {Object} data
     */
    AdminTab.prototype.tabAdd = function (data) {
        var that = this;
        var _config = that.config;
        if (!data.href) {
            return;
        }
        var tabIndex = that.exists(data.id);
        var waitLoadIndex;

        if (tabIndex === -1) {
            if (_config.openWait) {
                // waitLoadIndex = layer.load(2);
            }
            globalTabIdIndex++;
            var $title = $('<li data-id="' + data.id + '"></li>');
            $title.data('data', data);
            if (data.icon !== undefined) {
                var icon = $('<i class="fa ' + data.icon + '" aria-hidden="true"></i>');
                $title.append(icon);
            }
            var txt = $('<cite>' + data.title + '</cite>');
            $title.append(txt);
            if (_config.closed) {
                var closeT = $('<i class="fa fa-times" data-id="' + data.id + '"></i>');
                $title.append(closeT);
            }
            ELEM.titleBox.append($title);
            var content = '<div class="admin-tab-item" data-id="' + data.id + '"><iframe src="'
                + data.href + '" data-id="' + data.id + '"></iframe></div>';
            //添加tab
            ELEM.contentBox.append(content);

            //iframe 自适应
            ELEM.contentBox.find('iframe[data-id=' + data.id + ']').each(function () {
                $(this).height(ELEM.contentBox.height());
            });
            if (_config.closed) {
                //监听关闭事件
                ELEM.titleBox.find('li').children('i.fa-times[data-id=' + data.id + ']').on('click', function () {
                    that.tabDelete($(this).data('id'));
                    if (_config.contextMenu) {
                        $(document).find('div.uiba-contextmenu').remove(); //移除右键菜单dom
                    }
                });
            }
            //切换到当前打开的选项卡
            that.tabChange(data.id);
            if (data.id) {
                $.cookie("dataId", data.id);
            }
            ELEM.contentBox.find('iframe[data-id=' + data.id + ']').on('load', function () {
                //debugger;
                if (_config.openWait) {
                    // layer.close(waitLoadIndex);
                }
            });
        } else {
            that.tabChange(data.id);
            //自动刷新
            if (_config.autoRefresh) {
                _config.elem.find('div.admin-tab-content > div').eq(tabIndex).children('iframe')[0].contentWindow.location.reload();
            }
        }
        if (_config.contextMenu) {
            ELEM.titleBox.find('li').on('contextmenu', function (e) {
                var $that = $(e.target);
                e.preventDefault();
                e.stopPropagation();

                var $target = e.target.nodeName === 'LI' ? e.target : e.target.parentElement;
                //判断，如果存在右键菜单的div，则移除，保存页面上只存在一个
                if ($(document).find('div.admin-contextmenu').length > 0) {
                    $(document).find('div.admin-contextmenu').remove();
                }
                //创建一个div
                var div = document.createElement('div');
                //设置一些属性
                div.className = 'admin-contextmenu';
                div.style.width = '130px';
                div.style.backgroundColor = 'white';

                var ul = '<ul>';
                ul += '<li data-target="refresh" title="刷新当前选项卡"><i class="fa fa-refresh" aria-hidden="true"></i> 刷新</li>';
                ul += '<li data-target="closeCurrent" title="关闭当前选项卡"><i class="fa fa-close" aria-hidden="true"></i> 关闭当前</li>';
                ul += '<li data-target="closeOther" title="关闭其他选项卡"><i class="fa fa-window-close-o" aria-hidden="true"></i> 关闭其他</li>';
                ul += '<li data-target="closeAll" title="关闭全部选项卡"><i class="fa fa-window-close-o" aria-hidden="true"></i> 全部关闭</li>';
                ul += '</ul>';
                div.innerHTML = ul;
                div.style.top = e.pageY + 'px';
                div.style.left = e.pageX + 'px';
                //将dom添加到body的末尾
                document.getElementsByTagName('body')[0].appendChild(div);

                //获取当前点击选项卡的id值
                var id = $($target).data('id');
                var $context = $(document).find('div.admin-contextmenu');
                if ($context.length > 0) {
                    $context.eq(0).children('ul').children('li').each(function () {
                        var $that = $(this);
                        //绑定菜单的点击事件
                        $that.on('click', function () {
                            //获取点击的target值
                            var target = $that.data('target');
                            //
                            switch (target) {
                                case 'refresh': //刷新当前
                                    that.refreshPage(id);
                                    break;
                                case 'closeCurrent': //关闭当前
                                    if (id != '0') {
                                        that.tabDelete(id);
                                    }
                                    break;
                                case 'closeOther': //关闭其他
                                    ELEM.titleBox.children('li').each(function () {
                                        var $t = $(this);
                                        var id1 = $t.data('id');
                                        if (id1 != id && id1 !== undefined && id1 != '0') {
                                            that.tabDelete(id1);
                                        }
                                    });
                                    break;
                                case 'closeAll': //全部关闭
                                    ELEM.titleBox.children('li').each(function () {
                                        var $t = $(this);
                                        if ($t.data('id') != '0') {
                                            that.tabDelete($t.data('id'));
                                        }
                                    });
                                    break;
                            }
                            //处理完后移除右键菜单的dom
                            $context.remove();
                        });
                    });

                    $(document).on('click', function () {
                        $context.remove();
                    });
                }
                return false;
            });
        }
    };

    AdminTab.prototype.tabDelete = function (id) {
        var leftNavOne = $.cookie("leftNavOne");
        if (leftNavOne) {
            var leftNavOneId = JSON.parse(leftNavOne).id;
            if (leftNavOneId == id) {
                $.cookie("leftNavOne", "");
            }
        }
        var contentItem = ELEM.contentBox.find('.admin-tab-item[data-id=' + id + ']');
        var titleItem = ELEM.titleBox.find('li[data-id=' + id + ']');
        if (contentItem.hasClass('admin-show')) {
            var _id = contentItem.prev().data('id');
            this.tabChange(_id);
        }
        contentItem.remove();
        titleItem.remove();
    };

    AdminTab.prototype.tabChange = function (id) {
        var contentItem = ELEM.contentBox.find('.admin-tab-item[data-id=' + id + ']');
        var titleItem = ELEM.titleBox.find('li[data-id=' + id + ']');
        if (!contentItem.hasClass('admin-show')) {
            ELEM.contentBox.find('.admin-show').removeClass('admin-show');
            ELEM.titleBox.find('.admin-tab-selected').removeClass('admin-tab-selected');
            contentItem.addClass('admin-show');
            titleItem.addClass('admin-tab-selected');
        }
    };

    AdminTab.prototype.refreshPage = function (id) {
        // var src = ELEM.contentBox.find('iframe[data-id=' + id + ']')[0].src;
        ELEM.contentBox.find('iframe[data-id=' + id + ']')[0].contentWindow.location.reload();
    };

    var navbar = new Navbar();
    var admintab = new AdminTab();

    window.navbar = navbar;
    window.admintab = admintab;
})(window, jQuery);